﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static KMS自动激活.OsLists;
using System.Collections;


namespace KMS自动激活
{
    //public delegate bool CallBack(string input, string args);


    public partial class Form1 : Form
    {

        private string server = "kms.03k.org:1688";
        private readonly static MyShell shell = new MyShell();
        private bool isDebug;
        public Form1()
        {
            InitializeComponent();

            Init();
        }

        private void Init()
        {
            //this.Visible = false;
            //this.ShowInTaskbar = false;
            this.Icon = Properties.Resources.shell32_00018;
            this.Opacity = 0;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Text = $"{Application.ProductName} {Application.ProductVersion}";
            //this.Text = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name} {Application.ProductVersion}";
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.MinimizeBox = false;
            this.MaximizeBox = false;
            this.Size = new System.Drawing.Size(500, 400);
            //this.AcceptButton = this.button_activation;
            this.btn_activation.Text = "激活 Windows";
            //this.button_activation.Size=new System.Drawing.Size(this.Width/2, 50);
            //this.button_activation.Location = new System.Drawing.Point(this.Width / 2 - button_activation.Width / 2, 5);
            this.btn_activation.Size = new System.Drawing.Size(this.Width - 28, 40);
            this.btn_activation.Location = new System.Drawing.Point(5, 5);
            this.txt_log.Location = new System.Drawing.Point(5, btn_activation.Top + btn_activation.Height + 5);
            this.txt_log.Size = new System.Drawing.Size(this.btn_activation.Width, this.Height - this.txt_log.Top - 45);
            this.txt_log.ReadOnly = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //this.textBox1.Size = new System.Drawing.Size(this.Size.Width, this.Size.Height);
            OsLists osList= new OsLists();
            if (osList.GetKey()==null)
            {
                UpdateLog(new object[] { $"{osList.GetWinVer()}\n\r\n" });
                this.Opacity = 1;
                UpdateLog(new object[] { "激活程序不支持此系统！" });
                return;
            }
            Debug.Print(osList.GetKey());
            string[] args = Environment.GetCommandLineArgs();
            if (args.Length > 1)
            {
                server = GetValue("server")??server;
                isDebug = GetValue("debug") == "true";
                string mode = GetValue("mode")??"normal";
                switch (mode.ToLower())
                {
                    case "slient":
                        if (isDebug)
                        {
                            this.Opacity = 1;
                        }
                        else
                        {
                            this.Hide();
                            this.ShowInTaskbar = false;
                        }

                        this.txt_log.Clear();
                        Task t1 = Task.Run(new Action(() =>
                        {
                            Kms_Active();
                            if (!isDebug)
                                Environment.Exit(0);
                        }));
                        return;
                    case "help":
                        this.Opacity = 1;
                        btn_activation.Enabled = false;
                        ShowHelp();
                        return;
                }

                string GetValue(string match)
                {
                    string value = null;
                    foreach (string arg in args)
                    {
                        if (Array.IndexOf(args, arg) == 0)
                            continue;
                        if (arg.StartsWith($"/{match}="))
                            value = arg.Substring(match.Length + 2);
                    }
                    return value;
                }
            }
            this.Opacity = 1;
            Task t2 = Task.Run(new Action(()=>Kms_Active(true)));
        }

        /// <summary>
        /// 激活函数
        /// </summary>
        /// <param name="checkActive">设置true只检查激活状态</param>
        private void Kms_Active(bool checkActive = false)
        {
            UpdateControlStatus(false);
            ActiveWindows(checkActive);
            UpdateControlStatus(true);
        }

        /// <summary>
        /// 设置button安装状态
        /// </summary>
        /// <param name="enabled"></param>
        private void UpdateControlStatus(bool enabled)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(()=> UpdateControlStatus(enabled)));
            }
            else
            {
                btn_activation.Enabled= enabled;
            }
        }

        /// <summary>
        /// 激活windows
        /// </summary>
        /// <param name="checkActive">设置true只检查激活状态</param>
        private void ActiveWindows(bool checkActive=false)
        {
            DateTime startTime= DateTime.Now;
            OsLists osLists= new OsLists();

            string kms_cmd = $"cscript.exe slmgr.vbs";
            UpdateLog(new object[] { $"{osLists.GetWinVer()}\n\r\n" });
            if (!checkActive)
            {
                UpdateLog(new object[] { "开始激活计算机，请稍后...\r\n" });
                //获取当前激活信息
                Dictionary<string, string> infos = GetInfos(kms_cmd);
                //安装key
                if (infos["KEY"] == null)
                    Run("/ipk");
                //设置kms域名
                Run("/skms");
                //执行ato参数，激活
                Run("/ato");
                //清除kms域名
                Run("/ckms");
                //清除KMS计算机地址
                ClearHostAddress(infos);
                //执行dlii参数，查看授权状态
                Run($"/dli");
            }
            //执行xpr参数，获取激活状态
            Run($"/xpr");

            int sTime = (DateTime.Now - startTime).Seconds;
            double msTime = (DateTime.Now - startTime).Milliseconds;

            UpdateLog(new object[] { $"总计用时：{sTime}.{msTime}秒" });

            void Run(string args){
                bool output = true;
                if (isDebug)
                {
                    UpdateLog(new object[] { $"{kms_cmd} {args}" });
                }
                else
                {
                    switch (args)
                    {
                        case "/skms":
                            output = false;
                            break;
                        case "/ckms":
                            output = false;
                            break;
                        default:
                            break;
                    }
                }
                switch (args)
                {
                    case "/ipk":
                        args += $" {osLists.GetKey()}";
                        break;
                    case "/skms":
                        args += $" {server}";
                        break;
                    default:
                        break;
                }
                MyShell.CallBack callBack = new MyShell.CallBack(UpdateLog);
                shell.RunCmd(UpdateLog, null, kms_cmd, args, $"{Environment.GetEnvironmentVariable("WinDir")}\\System32",true,false,ProcessWindowStyle.Hidden,output);
                if (output)
                    UpdateLog(new object[] { "\r" });
                Thread.Sleep(500);
            }
        }

        private Dictionary<string,string> GetInfos(string kms_cmd)
        {
            Dictionary<string, string> infos = new Dictionary<string, string>
            {
                ["激活ID"] = null,
                ["程序ID"] = null,
                ["KEY"] = null
            };
            int idFlag = 1;
            shell.RunCmd(ReadID, null, kms_cmd, "/dlv", $"{Environment.GetEnvironmentVariable("WinDir")}\\System32");
            return infos;
            bool ReadID(object[] args)
            {
                string pattern = @"(?<=:).*";
                Regex regex = new Regex(pattern);
                string input = (string)args.FirstOrDefault()??string.Empty;
                //infos["激活 ID"] = regex.Match("激活 ID:").Groups[1].Value;
                //infos["激活 ID"] = regex.Match("应用程序 ID:").Groups[1].Value;
                if (input.StartsWith("激活 ID:"))
                {
                    infos["激活ID"] = regex.Match(input).Groups[0].Value.Trim();
                    idFlag++;
                }

                if (input.StartsWith("应用程序 ID:"))
                {
                    infos["程序ID"] = regex.Match(input).Groups[0].Value.Trim();
                    idFlag++;
                }
                if (input.StartsWith("部分产品密钥:"))
                {
                    infos["KEY"] = regex.Match(input).Groups[0].Value.Trim();
                    idFlag++;
                }
                if (idFlag > 3)
                {
                    return true;
                }
                return false;
            }
        }
        private void ClearHostAddress(Dictionary<string,string> infos)
        {
            if (isDebug)
                UpdateLog(new object[] { "清除 KMS计算机IP地址" });
            try
            {
                string idKey;
                if (infos["程序ID"] == null)
                    return;
                idKey = $"\\{infos["程序ID"]}";
                if (infos["激活ID"] == null)
                    return;
                idKey += $"\\{infos["激活ID"]}";

                string rootKey = $"S-1-5-20\\Software\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform{idKey}";
                string keyName = "DiscoveredKeyManagementServiceIpAddress";
                RegistryKey hku = Registry.Users;
                RegistryKey hkID = hku.OpenSubKey(rootKey,true);
                if (hkID != null)
                {
                    hkID.SetValue(keyName, "");
                    if (isDebug)
                        UpdateLog(new object[] { "KMS计算机IP地址成功清除\r\n" });
                }
                else
                {
                    if (isDebug)
                        UpdateLog(new object[] { "KMS计算机IP地址无需清除\r\n" });
                }
                
            }
            catch (Exception ex)
            {
                if (isDebug)
                    UpdateLog(new object[] { $"KMS计算机IP地址清除失败\r\n{ex.Message}\r\n{ex}\r\n\r\n" });
                return;
            }

        }
        private bool UpdateLog(object[] args)
        {
         
            if (InvokeRequired)
            {
                Invoke(new Action(()=> UpdateLog(args)));
            }
            else
            {
                string input = (string)args.FirstOrDefault();
                if (string.IsNullOrEmpty(input))
                    return false;
                string[] skipString = { "Microsoft (R) Windows Script" , "版权所有(C)" };       //"许可证状态: 已授权","计算机已永久激活"
                foreach (string str in skipString)
                {
                    if (input.StartsWith(str))
                        return false;
                }
                this.txt_log.AppendText($"{input}\r\n");
            }
            return false;
        }

        private void ShowHelp()
        {
            List<string> helpMsg = new List<string>()
            {
                "调用方法：",
                "默认模式：/mode=normal 说明：有窗口，不自动激活",
                "静默模式：/mode=slient 无窗口自动激活并退出",
                "调试模式：/debug=true 会强制显示窗口,部分内容只显示不执行",
                "自定义服务器：/server=<server> 自定义服务器",
            };

            txt_log.Clear();
            helpMsg.ForEach (item =>
            {
                txt_log.AppendText($"{item}\r\n\r\n");
            }) ;
                ///"调用方法",
                /// /mode=normal 默认模式，有窗口，不自动激活
                /// /mode=slient 静默调用，无窗口自动激活并退出
                /// /debug=true 调试模式，会强制显示窗口
                /// /server=<server> 可以自定义服务器
                /// </summary>
        }

        private void button_activation_Click(object sender, EventArgs e)
        {
            Task t = Task.Run(new Action(() => Kms_Active()));
        }

        private void btn_Help_Click(object sender, EventArgs e)
        {
            ShowHelp();
        }
    }

    /// <summary>
    /// 数据匹配类
    /// 正则匹配
    /// </summary>
    public class DataMatch
    {
        //正则确实数据是否匹配，返回bool
        public bool IsMatch(string input, string pattern)
        {
            if (string.IsNullOrEmpty(pattern)) return false;
            pattern = pattern.Replace("+", "\\+");
            pattern = pattern.Replace(".", "\\.");
            Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
            Match match = r.Match(input);
            return match.Success;
        }

        //正则匹配数据，返回List<string>
        public List<string> MatchData(string input, string pattern)
        {
            if (string.IsNullOrEmpty(pattern)) return null;
            Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
            List<string> rList = new List<string>();
            MatchCollection matchs = r.Matches(input);
            foreach (Match item in matchs)
            {
                if (!string.IsNullOrEmpty(item.Value))
                {
                    rList.Add(item.Value);
                }
            }
            return rList;
        }
    }

    /// <summary>
    /// 进程运行类
    /// </summary>
    public class MyShell
    {
        private readonly int RUN_CMD = 0x01;
        private readonly int RUN_FILE = 0x02;
        public delegate bool CallBack(object[] args = null);
        public delegate void CallBackMsg(int x, string args);
        public MyLog myLog = new MyLog();
        public DataMatch dataMatch = new DataMatch();

        //通过进程名确认进程是否存在，存在返回PID
        public bool ProcessExist(string proName, string extensions = "exe", CallBack callbackFunc = null, object[] callbackArgs = null)
        {
            if (!string.IsNullOrEmpty(proName))
            {
                int result = 0;
                proName = proName.Replace("*", ".*").Replace("?", ".");
                string[] watchs = proName.Split(',');
                Process[] ps = Process.GetProcesses();
                foreach (string watch in watchs)
                {
                    string value = null;
                    if (watch.EndsWith($".{extensions}", StringComparison.OrdinalIgnoreCase))
                        value = watch.Substring(0, watch.Length - 4);
                    foreach (Process p in ps)
                    {
                        if (dataMatch.IsMatch(p.ProcessName, value))
                        {
                            result += p.Id;
                        }
                    }
                }
                callbackFunc?.Invoke(callbackArgs);

                return result > 0;
            }
            return false;
        }

        //通过PID确认进程是否存在，存在返回PID
        public int ProcessExist(int PID)
        {
            Process p = Process.GetProcessById(PID);
            return p.Id;
        }

        public void ProcessWait(string proName, string extensions = "exe", int watchInterval = 500, CallBack callbackFunc = null, object[] callbackArgs = null)
        {
            while (true)
            {
                if (ProcessExist(proName, extensions))
                {
                    return;
                }
                Thread.Sleep(watchInterval);
                callbackFunc?.Invoke(callbackArgs);
            }
        }

        public void ProcessClose(string proName, string extensions = "exe", int watchInterval = 500, CallBack callbackFunc = null, object[] callbackArgs = null)
        {
            while (true)
            {
                if (!ProcessExist(proName, extensions))
                {
                    return;
                }
                Thread.Sleep(watchInterval);
                callbackFunc?.Invoke(callbackArgs);
            }
        }

        //Kill进程byName
        public bool ProcessKill(string proName, CallBack callbackFunc = null, object[] callbackArgs = null)
        {
            Process[] ps = Process.GetProcessesByName(proName);
            if (ps == null)
            {
                return false;
            }
            foreach (Process p in ps)
            {
                callbackFunc?.Invoke(callbackArgs);
                p.Kill();
            }
            return true;
        }

        //Kill进程byPID
        public bool ProcessKill(int proID)
        {
            try
            {
                Process p = Process.GetProcessById(proID);
                if (p == null)
                {
                    return false;
                }
                else
                {
                    p.Kill();
                }
            }
            catch (Exception)
            {
            }
            return true;
        }

        //运行命令函数，最终调用Run函数，返回int pid
        public int RunCmd(CallBack lpProcFunc, object[] callbackArgs, string cmdLine, string args = null, string workingPath = null, bool waitExit = false,
            bool useShellExecute = false, ProcessWindowStyle WindowStyle = ProcessWindowStyle.Hidden, bool standardOutput = true, bool onlineOutput = true)
        {
            //int RUN_CMD = 0;
            if (cmdLine != null)
            {
                int result = Run(lpProcFunc, callbackArgs, RUN_CMD, cmdLine, args, workingPath, waitExit, useShellExecute,
                    WindowStyle, standardOutput, onlineOutput);
                return result;
            }
            else
            {
                return 0;
            }
        }

        //运行命令函数，最终调用Run函数，返回int pid
        public int RunCmd(string cmdLine, string args = null, string workingPath = null, bool waitExit = false,
            bool useShellExecute = false, ProcessWindowStyle WindowStyle = ProcessWindowStyle.Hidden, bool standardOutput = true, bool onlineOutput = true)
        {
            //int RUN_CMD = 0;
            if (cmdLine != null)
            {
                int result = Run(null, null, RUN_CMD, cmdLine, args, workingPath, waitExit, useShellExecute, WindowStyle, standardOutput, onlineOutput);
                return result;
            }
            else
            {
                return 0;
            }
        }

        //运行文件函数，最终调用Run函数，返回int pid
        public int RunFile(CallBack lpProcFunc, object[] callbackArgs, string fileFullName, string args = null, string workingPath = null, bool waitExit = false,
            bool useShellExecute = false, ProcessWindowStyle WindowStyle = ProcessWindowStyle.Hidden, bool delFlag = false, bool standardOutput = false, bool onlineOutput = false)
        {
            //int RUN_FILE = 1;
            //List<string> result = null;
            FileInfo fiInfo = new FileInfo(fileFullName);
            if (fiInfo.Exists)
            {
                int result = Run(lpProcFunc, callbackArgs, RUN_FILE, fiInfo.FullName, args, workingPath, waitExit, useShellExecute, WindowStyle, standardOutput, onlineOutput);
                fiInfo.Refresh();
                if (delFlag && fiInfo.Exists)
                {
                    try
                    {
                        fiInfo.Delete();
                        fiInfo.Refresh();
                    }
                    catch (Exception e)
                    {
                        Debug.Print(myLog.Format(2, e.Message));
                    }
                }
                return result;
            }
            else
            {
                return 0;
            }
        }

        //运行文件函数，最终调用Run函数，返回int pid
        public int RunFile(string fileFullName, string args = null, string workingPath = null, bool waitExit = false,
            bool useShellExecute = false, ProcessWindowStyle WindowStyle = ProcessWindowStyle.Hidden, bool delFlag = false, bool standardOutput = false, bool onlineOutput = false)
        {
            //int RUN_FILE = 1;
            //List<string> result = null;
            FileInfo fiInfo = new FileInfo(fileFullName);
            if (fiInfo.Exists)
            {
                int result = Run(null, null, RUN_FILE, fiInfo.FullName, args, workingPath, waitExit, useShellExecute,
                    WindowStyle, standardOutput, onlineOutput);
                fiInfo.Refresh();
                if (delFlag && fiInfo.Exists)
                {
                    try
                    {
                        fiInfo.Delete();
                        fiInfo.Refresh();
                    }
                    catch (Exception e)
                    {
                        Debug.Print(myLog.Format(2, e.Message));
                    }
                }
                return result;
            }
            else
            {
                return 0;
            }
        }

        //运行过程函数，返回int pid
        private int Run(CallBack procFunc, object[] proFuncArgs, int runType, string text, string args, string workingPath,
            bool waitExit, bool useShellExecute, ProcessWindowStyle WindowStyle, bool standardOutput, bool onlineOutput)
        {
            text = text ?? string.Empty;
            args = args ?? string.Empty;
            workingPath = workingPath ?? Environment.CurrentDirectory;
            //List<string> resultList = new List<string>();
            int PID = 0;
            using (Process cmdProcess = new Process())
            {
                switch (runType)
                {
                    case 0x01:
                        cmdProcess.StartInfo.FileName = Environment.GetEnvironmentVariable("ComSpec");
                        cmdProcess.StartInfo.Arguments = "/C " + text + " " + args;
                        break;
                    case 0x02:
                        cmdProcess.StartInfo.FileName = text;
                        cmdProcess.StartInfo.Arguments = args;
                        break;
                    default:
                        break;
                }
                //设置工作目录
                cmdProcess.StartInfo.WorkingDirectory = workingPath;
                //关闭Shell的使⽤，如果需运行非exe后缀的exe文件则需设置为false
                cmdProcess.StartInfo.UseShellExecute = useShellExecute;
                if (standardOutput)
                {

                    //设置窗口编码
                    //process.StartInfo.StandardOutputEncoding = Encoding.Default;
                    //重新定向标准输⼊，输⼊，错误输出
                    cmdProcess.StartInfo.RedirectStandardInput = true;
                    cmdProcess.StartInfo.RedirectStandardOutput = true;
                    cmdProcess.StartInfo.RedirectStandardError = true;
                }
                //不创建窗口
                cmdProcess.StartInfo.CreateNoWindow = true;
                //设置调用程序显示状态，true显示
                cmdProcess.StartInfo.WindowStyle = WindowStyle;
                try
                {
                    //开始
                    if (!cmdProcess.Start()) return 0;
                    PID = cmdProcess.Id;
                    Debug.Print(myLog.Format(myLog.INFO_DATE, $"Current process pid: {PID}"));
                    //直接运行方法，最后需要加exit
                    //process.StandardInput.WriteLine("ping 192.168.31.1");
                    //cmdProcess.StandardInput.WriteLine("exit");

                    bool isProceLoop = true;
                    //获取结果
                    if (standardOutput)
                    {
                        if (onlineOutput)
                        {
                            while (!cmdProcess.StandardOutput.EndOfStream)
                            {
                                string outLine = cmdProcess.StandardOutput.ReadLine();
                                Debug.Print(myLog.Format(myLog.INFO_DATE, outLine));
                                object[] tempArgs = null;
                                //myLog.FileWriteLine(0, outLine);
                                if (isProceLoop)
                                {
                                    if (procFunc != null)
                                    {
                                        if (proFuncArgs == null)
                                            tempArgs = new object[] { outLine, PID.ToString() };
                                        if (procFunc(tempArgs))
                                        {
                                            isProceLoop = false;
                                            return PID;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            //myLog.FileWriteLine(0, "Wait output ReadToEnd...");
                            string result = cmdProcess.StandardOutput.ReadToEnd();
                            string[] results = result.Replace("\r\n", "\n").Replace("\t", "").Split('\n');
                            //ProcFunc?.Invoke(item);       //该方法可以直接判断函数是否为null，不为null运行
                            foreach (string outLine in results)
                            {
                                object[] tempArgs = null;
                                //myLog.FileWriteLine(0, "Output: " + outLine);
                                if (isProceLoop)
                                {
                                    //执行回调函数
                                    if (proFuncArgs == null)
                                        tempArgs = new object[] { outLine, PID.ToString() };
                                    if (procFunc(tempArgs))
                                    {
                                        isProceLoop = false;
                                        return PID;
                                    }
                                }
                            }
                            //resultList.AddRange(results);
                        }
                    }
                    if (waitExit)
                    {
                        //myLog.FileWriteLine(0, "Waiting for the process to exit...");
                        cmdProcess.WaitForExit();
                    }
                }
                catch (Exception e)
                {
                    myLog.FileWriteLine(2, e.ToString());
                }
            }
            //等待按任意键关闭
            //Console.ReadKey();
            return PID;
        }
    }

    /// <summary>
    /// 日志类
    /// </summary>
    public class MyLog
    {
        public readonly int INFO_DATE = 0x01;
        public readonly int WARN_DATE = 0x02;
        public readonly int ERROR_DATE = 0x03;
        public readonly int INFO = 0x04;
        public readonly int WARN = 0x05;
        public readonly int ERROR = 0x06;
        private readonly string ProcessName = Process.GetCurrentProcess().ProcessName;
        private readonly string ProcessStartPath = Environment.CurrentDirectory;
        //private readonly string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
        public string WorkPath { get; set; }
        public System.IO.FileInfo LogFile { get; set; }
        //private ResFileInfo fiLogFile = new ResFileInfo(Environment.GetEnvironmentVariable("Temp") + "\\" + assemblyName + ".log");

        public MyLog(string logFile = null, string workPath = null)
        {
            this.LogFile = logFile == null ? new System.IO.FileInfo($"{ProcessStartPath}\\{ProcessName}.log") : new System.IO.FileInfo(logFile);
            this.WorkPath = workPath ?? Environment.CurrentDirectory;
        }

        //格式化日志输出时日期和日志class
        public string Format(int classValue, string logText)
        {
            string res;
            string logDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

            // value 大于3则减3，保持值为1-3
            int value = classValue > 3 ? classValue - 3 : classValue;
            switch (value)
            {
                case 0x01:
                    res = "INFO";
                    break;
                case 0x02:
                    res = "WARN";
                    break;
                case 0x03:
                    res = "ERROR";
                    break;
                default:
                    res = "INFO";
                    break;
            }
            // value 大于3返回无日期的log标志
            string flag = classValue > 3 ? $"[{res}]" : $"{logDate} [{res}]";

            //包含日期、日志class，日志内容
            return string.Format("{0} {1}", flag, logText);
        }


        //控制台输出日志函数，行输出，重载
        public void ConWriteLine(string text = null, int left = 0, int top = 0)
        {
            if (left > 0 || top > 0)
            {
                //调整输出位置
                Console.SetCursorPosition(left, top);
            }
            Console.WriteLine(text);
        }

        //控制台输出日志函数，行输出，重载
        public void ConWriteLine(int classValue, string text = null, int left = 0, int top = 0)
        {
            if (left > 0 || top > 0)
            {
                //调整输出位置
                Console.SetCursorPosition(left, top);
            }
            Console.WriteLine(Format(classValue, text));
        }

        //控制台输出日志函数，重载
        public void ConWrite(string text, int left = 0, int top = 0)
        {
            if (left > 0 || top > 0)
            {
                //调整输出位置
                Console.SetCursorPosition(left, top);
            }
            Console.Write(text);
        }

        //控制台输出日志函数，重载
        public void FileWrite(int classValue, string text)
        {
            try
            {
                ConWriteLine(classValue, text);
                using (StreamWriter sw = LogFile.AppendText())
                {
                    sw.Write(Format(classValue, text));
                }
            }
            catch (Exception e)
            {
                Debug.Print(Format(ERROR_DATE, e.ToString()));
            }
        }


        //日志文件输出日志函数
        public void FileWrite(System.IO.FileInfo fi, int classValue, string text)
        {
            try
            {
                ConWriteLine(classValue, text);
                using (StreamWriter sw = fi.AppendText())
                {
                    sw.Write(Format(classValue, text));
                }
            }
            catch (Exception e)
            {
                Debug.Print(Format(ERROR_DATE, e.ToString()));
            }
        }

        //日志文件输出日志函数，行输出，重载
        public void FileWriteLine(int classValue, string text)
        {
            try
            {
                ConWriteLine(classValue, text);
                using (StreamWriter sw = LogFile.AppendText())
                {
                    sw.WriteLine(Format(classValue, text));
                }
            }
            catch (Exception e)
            {
                Debug.Print(Format(ERROR_DATE, e.ToString()));
            }
        }

        //日志文件输出日志函数，行输出，重载
        public void FileWriteLine(System.IO.FileInfo fi, int classValue, string text)
        {
            try
            {
                ConWriteLine(classValue, text);
                using (StreamWriter sw = fi.AppendText())
                {
                    sw.WriteLine(Format(classValue, text));
                }
            }
            catch (Exception e)
            {
                Debug.Print(Format(ERROR_DATE, e.ToString()));
            }
        }
    }
}
